package com.woniu.util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zgc  2024/6/25
 */

@Component
@Data
@ConfigurationProperties(prefix = "jwt")
public class JwtUtil {
    private String alg;
    private String typ;
    private long expire;
    private String id;
    private String subject;
    private String salt;


    // 生成token
    public String createToken(String userName) {
        // 1: 创建builder
        JwtBuilder builder = Jwts.builder();
        // 2: 设置头部
        builder.setHeaderParam("alg", alg);
        builder.setHeaderParam("typ", typ);
        // 3：设置载荷
        long time = 60 * 1000 * expire;
        
        builder.setId(id);
        builder.setSubject(subject);
        builder.setExpiration(new Date(System.currentTimeMillis() + time));
        // 可以设置自定义的内容
        builder.claim("accountName", userName);

        // : 设置验签
        builder.signWith(SignatureAlgorithm.HS256, salt);

        // 组合成生token
        String token = builder.compact();
        return token;
    }
    
    
    //解析token
    public String parseToken(String token) {
        try {
            // 得到解析器
            JwtParser parser = Jwts.parser();
            // 设置盐
            Jws<Claims> claimsJws = parser.setSigningKey(salt).parseClaimsJws(token);
            // 2：得到载荷
            Claims body = claimsJws.getBody();
            String userName = (String) body.get("userName");
            return userName;
        } catch (ExpiredJwtException e) {
            throw new ExpiredJwtException(null, null, "对不起token已经过期！", e);
        } catch (SignatureException e) {
            throw new SignatureException("token(密钥)不正确", e);
        } catch (RuntimeException e) {
            throw new RuntimeException("token解析异常！", e);
        }
    }

}
